<style lang="less" scoped>
.main-keyword-group {
    .btn-wrap {
        padding: 5px 0;
    }
    .online,
    .offline {
        margin-left: 0;
    }
    .second-row .manage-templet {
        margin-top: 5px;
    }
    .group {
        display: inline-block;
        vertical-align: top;
    }
}
</style>
<template>
    <div>
        <div class="main main-keyword-group">
            <div class="main-header">
                <el-breadcrumb>
                    <el-breadcrumb-item :to="{ path: '/tickets' }">维修管理</el-breadcrumb-item>
                    <el-breadcrumb-item>维修管理</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div class="main-filters">
                <el-form :inline="true" :model="query">
                    <el-form-item>
                        <el-radio-group v-model="query.status">
                            <el-radio-button label="all">全部</el-radio-button>
                            <el-radio-button
                                v-for="(item, id) in statusAlias"
                                :label="id"
                            >{{item.name}}</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="维修类型">
                        <el-select v-model="query.type">
                            <el-option label="全部" value="all" key=""></el-option>
                            <el-option
                                v-for="item in types"
                                :label="item"
                                :value="item"
                                :key="item"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <div class="main-actions">
                <div class="main-actions-label">
                    共<em>{{itemsData.pagination.total}}</em>条
                </div>
            </div>
            <el-table
                border
                element-loading-text="Loading..."
                v-loading.body="!itemsData.$resolved"
                :data="itemsData.items"
                @sort-change="onSortItems"
                @selection-change="onSelect"
            >
                <el-table-column width="200" prop="type" label="维修信息" inline-template>
                    <div>
                        <span>维修单号：{{row.id + 10000}}</span><br/>
                        <span>单据类型：{{row.ticket_type}}</span><br/>
                        <span>维修类别：{{row.type}}</span><br/>
                        <span>维修内容：{{row.description}}</span><br/>
                        <span>备注：{{row.remark}}</span><br/>
                    </div>
                </el-table-column>
                <el-table-column label="人员信息"  width="200" inline-template>
                    <div>
                        <span>部门：{{row.department.name}}</span><br/>
                        <span>联系人：{{row.creator.name}}</span><br/>
                        <span>电话：{{row.phone}}</span><br/>
                        <span>分配人：{{row.allocator.name}}</span><br/>
                        <span>维修员：{{row.repairer.name}}</span><br/>
                        <span>确认人：{{row.checker.name}}</span><br/>
                    </div>
                </el-table-column>
                <el-table-column label="耗材信息"  width="250" inline-template>
                    <div>
                        <p v-for="item in row.goods" v-bind:key="item.id" >
                            {{item.batch.good.name}}-{{item.batch.id}}批次 ￥{{item.batch.price}} {{item.stock}}个
                        </p>
                    </div>
                </el-table-column>
                <el-table-column prop="reason" width="120" label="退回原因"></el-table-column>
                <el-table-column width="120" label="申请时间" inline-template>
                    <div>
                        <span>{{row.created_at | date}}</span>
                    </div>
                </el-table-column>
                <el-table-column width="120" label="完成时间" inline-template>
                    <div>
                        <span v-if="row.status === statusMap.COMPLETED">{{row.created_at | date}}</span>
                    </div>
                </el-table-column>
                <el-table-column width="100" prop="status" label="状态" inline-template>
                    <el-tag :type="statusAlias[row.status].icon">{{statusAlias[row.status].name}}</el-tag>
                </el-table-column>
                <!-- <el-table-column label="状态属性" width="100" inline-template>
                    <div>
                        <el-tag type="success" v-if="row.status === 1">已上架</el-tag>
                        <el-tag type="warning" v-else>已下架</el-tag>
                    </div>
                </el-table-column> -->
                <!-- <el-table-column sortable="custom" prop="priority" label="排序"></el-table-column> -->
                <el-table-column label="操作" inline-template>
                    <div class="item-menus">
                        <el-button size="small" type="warning" v-if="row.status === statusMap.PENDING || row.status === statusMap.CALLBACK" @click="editItem(row, statusMap.ALLOCATED)">分配</el-button>
                        <el-button size="small" type="warning" v-if="row.status > statusMap.PENDING && row.status < statusMap.COMPLETED" @click="editItem(row, statusMap.CALLBACK, '退回')">退回</el-button>
                        <el-button size="small" type="warning" v-if="row.status === statusMap.ALLOCATED" @click="pushItem(row, statusMap.REPAIRED, '已完成')">确认完成</el-button>
                        <el-button size="small" type="danger" v-if="row.status === statusMap.REPAIRED && row.goods.length < 1" @click="showGoodListMethod(row)">录入耗材</el-button>
                        <el-button size="small" type="success" v-if="row.status >= statusMap.ALLOCATED && row.status < statusMap.REPAIRED" @click="printRepair(row)">打印维修单</el-button>
                        <el-button size="small" type="danger" v-if="row.status === statusMap.PENDING" @click="pushItem(row)">删除</el-button>
                        <!-- <el-button size="small" type="success" v-if="row.grand_id === 0" @click="editItem(row, 2)">新增子维修</el-button> -->
                    </div>
                </el-table-column>
            </el-table>

            <el-pagination
                v-if="itemsData.$resolved"
                layout="prev, pager, next, jumper"
                :total="itemsData.pagination.total"
                :current-page="query.page_num"
                :page-size="query.page_size"
                @current-change="onPageChange"
            >
            </el-pagination>

            <el-dialog
                :title="editData.title"
                :visible.sync="editDialogVisible"
                size="tiny"
            >
                <el-form :model="editData">
                    <el-form-item label="维修类别">
                        <el-select v-model="editData.type" disabled>
                            <el-option
                                v-for="item in types"
                                :label="item"
                                :value="item"
                                :key="item"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="地址">
                        <el-input v-model="editData.address" disabled placeholder="输入维修名"></el-input>
                    </el-form-item>
                
                    <el-form-item label="内容">
                        <el-input type="textarea" rows="3" v-model="editData.description" disabled placeholder="维修内容"></el-input>
                    </el-form-item>
                    <el-form-item v-if="this.editData.status === statusMap.CALLBACK" label="退回原因">
                        <el-input type="textarea" rows="2" v-model="editData.reason" placeholder="退回原因"></el-input>
                    </el-form-item>
                    <el-form-item label="维修员(请输入姓名搜索维修员)">
                        <el-select v-model="editData.repairer_id"
                            filterable
                            remote
                            reserve-keyword
                            placeholder="请输入姓名搜索维修员"
                            :remote-method="remoteMethod">
                            <el-option
                                v-for="item in repairs"
                                :label="item.name"
                                :value="item.id"
                                :key="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitEdit">确 定</el-button>
                </span>
            </el-dialog>

            <el-dialog
                title="耗材"
                :visible.sync="showGoodList"
                size="tiny"
            >
                <el-form :model="goodsList">
                    <el-form-item label="添加耗材">
                    <el-select
                        placeholder="输入物料名称或型号搜索"
                        style="width: 100%"
                        v-model="goodsList"
                        :remote-method="loadGoodsLzay"
                        :loading="!goods.$resolved"
                        :get-option-value="getTagOptionValue"
                        value-key="name"
                        filterable
                        multiple
                        remote
                    >
                        <!-- :key="item.name+item.types" -->
                        <el-option
                            v-for="item in goods.items"
                            :key="item.name"
                            :label="item.name"
                            :value="item"
                        />
                    </el-select>
                </el-form-item>
                    <el-form-item v-for="item in goodsList" v-bind:key="item.id" :label="item.name">
                        <el-input-number  v-model="item.stock" ></el-input-number>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="showGoodList = false">取 消</el-button>
                    <el-button type="primary" @click="addGoodList">确 定</el-button>
                </span>
            </el-dialog>
            <div id="printPage" style="margin:0 auto;" v-show="false">
                <p style="text-align: left">票据单号: {{repair.id + 10000}}</p>
                <p style="text-align: left">维修类型: {{repair.type}}</p>
                <p style="text-align: left">地点: {{repair.address}}</p>
                <p style="text-align: left">维修内容: {{repair.description}}</p>
                <p style="text-align: left">联系人: {{repair.creator ? repair.creator.name  : ''}}</p>
                <p style="text-align: left">电话: {{repair.phone}}</p>
                <p style="text-align: left">维修员: {{repair.repairer? repair.repairer.name : ''}}</p>
                <p style="text-align: left">耗材:_____________________________<br/>
                                            _________________________________<br/>
                                            _________________________________</p>
            </div>
        </div>
    </div>

</template>

<script>
import ListController from '../controllers/list';

import Repair from '../models/repair';
import GoodModel from '../models/good';
import User from '../models/user';
import Promise from 'bluebird';
import html2canvas from 'html2canvas'

export default new ListController({
    data() {
        return {
            ListModel: Repair,
            user: TTXS.user,
            query: {
                page_num: 1,
                page_size: 20,
                status: 'all',
                type: 'all',
            },

            repair: {
            },
            statusMap: {
                PENDING: Repair.PENDING,
                ALLOCATED: Repair.ALLOCATED,
                REPAIRED: Repair.REPAIRED,
                COMPLETED: Repair.COMPLETED,
                CALLBACK: Repair.CALLBACK            
            },
            statusAlias: {
                [Repair.PENDING]: {
                    icon: 'warning',
                    name: '待分配'
                },
                [Repair.ALLOCATED]: {
                    icon: 'success',
                    name: '已分配'
                },
                [Repair.REPAIRED]: {
                    icon: 'gray',
                    name: '已维修'
                },
                [Repair.CALLBACK]: {
                    icon: 'danger',
                    name: '已退回'
                },
                [Repair.COMPLETED]: {
                    icon: 'success',
                    name: '已完成'
                }
            },

            types: ['普通维修', '紧急维修'],
            repairs: [],

            goodsList: [],
            editData: {},
            goods: [],
            repair_id: 0,
            editDialogVisible: false,
            showGoodList: false
        };
    },
    methods: {
        beforeLoadItems() {
            return Promise.all([
                this.loadUsers()
            ]);
        },
        printRepair(row) {
            this.repair = row;
            setTimeout(() => {
                this.print();
            }, 500);
        },
        print() {
            var head_str = "<html><head><title></title></head><body>"; //先生成头部
            var foot_str = "</body></html>"; //生成尾部
            var older = document.body.innerHTML;
            var new_str = document.getElementById('printPage').innerHTML; //获取指定打印区域
            var old_str = document.body.innerHTML; //获得原本页面的代码
            document.body.innerHTML = head_str + new_str + foot_str; //构建新网页
            window.print(); //打印刚才新建的网页
            document.body.innerHTML = older; 
            window.location.reload();

            // console.log(document.getElementById('printPage'));

            // return html2canvas(document.getElementById('printPage'), {
            //     width: 100,
            //     height: 400,
            // }).then(canvas => {
            //     document.body.appendChild(canvas);
            //     // var head_str = "<html><head><title></title></head><body>"; //先生成头部
            //     // var foot_str = "</body></html>"; //生成尾部
            //     // var new_str = "<img src='"+canvas.toDataURL()+"'/>"
            //     // var older = document.body.innerHTML;

            //     // var old_str = document.body.innerHTML; //获得原本页面的代码
            //     // document.body.innerHTML = head_str + new_str + foot_str; //构建新网页
            //     // window.print(); //打印刚才新建的网页
            //     // document.body.innerHTML = older; 
            //     // window.location.reload();
            //     // return false;
            // });
        },
        debugItem(row) {
            this.$confirm('确认调试该项？')
            .then(() => {
                this.ListModel.update({
                    id: row.id,
                    status: 1
                }).$promise;
            })
            .catch(err => {
                throw new Error(err);
            });
        },
        pullItem(row) {
            this.$confirm('确认下线该项？')
            .then(() => {
                const params = Object.assign({}, row, {
                    id: row.id,
                    status: 0
                });
                this.ListModel.update(params).$promise;
            })
            .then(() => {
                this.$message({
                    message: '下线成功！',
                    type: 'success'
                });

                this.loadItems();
            })
            .catch(err => {
                this.$message.error(err);
            });
        },
        pushItem(row, status, msg) {
            this.$confirm('确认？' + msg)
            .then(() => {
                return this.ListModel.update({
                    id: row.id,
                    status: status
                }).$promise
                .then(() => {
                    this.loadItems();
                });
            })
            .catch(err => {
                throw new Error(err);
            });
        },
        
        deleteItem(row) {
            this.$confirm('确认删除该维修？')
            .then(() => {
                return this.ListModel.delete({
                    id: row.id
                }).$promise;
            })
            .then(() => {
                return this.loadItems();
            })
            .catch(err => {
                throw new Error(err);
            });
        },
        editItem(row, status) {
            this.editDialogVisible = true;
            this.editData = Object.assign({}, {type: '', address: '', description: ''}, row);
            this.editData.status = status;
        },
        submitEdit() {
            let params = null;
            let $submitPromise = null;

            if(this.editData.id > 0) {
                if(this.editData.status === this.statusMap.CALLBACK && !this.editData.reason) {
                    this.$message.info('请填写退回原因');
                    return;
                }
                $submitPromise = this.ListModel.update(this.editData).$promise;
            }
            else {
                params = Object.assign({}, this.editData);
                $submitPromise = this.ListModel.save(params).$promise;
            }

            $submitPromise
            .then(res => {
                if(res.code && res.code !== 200) {
                    this.$message.error(res.message);
                    return;
                }
                this.editDialogVisible = false;
                this.$message({
                    message: '提交成功！',
                    type: 'success'
                });
                this.loadItems();
            })
            .catch(err => {
                this.$message.error(err);
            });
        },
        remoteMethod(query) {
            console.log(query)
            return User.query({
                name: query,
                department_id: 2
            })
            .$promise
            .then(users => {
                this.repairs = users.items;
            });
        },
        loadUsers() {
            return User.query({
                department_id: 2
            })
            .$promise
            .then(users => {
                this.repairs = users.items;
            });
        },
        loadGoodsLzay(key) {
            clearTimeout(this.loadTagsTimer);
            this.loadTagsTimer = setTimeout(() => {
                this.loadGoods(key);
            }, 200);
        },
        loadGoods(key) {
            return GoodModel.query({
                q: String(key || '').trim(),
                page_size: 30
            })
            .$promise
            .then(goods => {
                this.goods = goods;

                goods.items.map(item => {
                    item.stock = 1;
                })
                return goods;
            })
            
        },
        getTagOptionValue(val) {
            if(typeof val === 'string') {
                return {
                    name: val
                };
            }

            return val;
        },
        showGoodListMethod(row) {
            this.repair_id = row.id
            this.showGoodList = true;
        },
        addGoodList() {
            return this.$confirm('确认耗材？')
            .then(() => {
                this.ListModel.update({
                    id: this.repair_id,
                    goods: this.goodsList
                }).$promise;
            })
            .then(() => {
                this.loadItems();

                this.showGoodList = false;
            })
        },
    }
});
</script>
